package com.wutianyi.favority.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wutianyi.favority.FavorityRepository;
import com.wutianyi.favority.bean.User;
import com.wutianyi.favority.service.FavorityServiceLocator;
import com.wutianyi.favority.utils.FavorityUtils;

/**
 * Servlet implementation class IndexServlet
 */
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static FavorityRepository repository = FavorityServiceLocator
			.getRepository();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public IndexServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		long uid = FavorityUtils.stringToLong(request.getParameter("uid"), -1);

		System.out.println(uid);

		if (-1 == uid) {
			return;
		}

		User user = repository.getUser(uid);

		if (null == user) {
			user = repository.createUser(uid);
		}
		request.setAttribute("uid", uid);
		request.setAttribute("folders", user.getFolders());
		request.setAttribute("recommends", repository.getRecommendLinks(uid));
		request.setAttribute("recommendUsers",
				repository.getRecommendUsers(uid));
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	@Override
	public void destroy() {
		super.destroy();
		repository.getGraphDb().shutdown();
	}

}
